/**
 * author:Administrator
 * date:2016/3/2
 * desc:TODO
 */
"use strict";

let Router = require('koa-router')
  , __pathPrefix = '/api/v1/location'
  , router = new Router({prefix: __pathPrefix});
module.exports = router.routes();
console.log('router:' + __pathPrefix + ',file=' + __filename);

let queryService = require('../../ddd/application/queryService');
let cmdService = require('../../ddd/application/cmdService');
let koabody = require('koa-better-body')();

let appUtil = require('../../common/appUtil.js');
let FormatOutput = require('../../common/FormatOutput.js');
let FormatError = require('../../common/FormatError.js');

/**
 * get location
 * get /api/v1/location         ==> 获取所有
 * get /api/v1/location?top=1   ==> 顶层
 * get /api/v1/location?pid=3   ==> 某个节点下所有child
 */
router.get('/', koabody, function*() {
  let top = this.query.top;
  if (!!top) return this.body = yield queryService.topLocation();

  let pid = this.query.pid;
  if (!!pid) {
    pid = parseInt(pid);
    return this.body = yield queryService.childLocation(pid);
  }

  this.body = yield queryService.allLocation();
});


/**
 * create location
 * post /api/v1/location
 * {name,pid}
 */
router.post('/', koabody, function*() {
  let user = yield appUtil.getUser(this);
  if (!user) return this.body = FormatOutput.payloadOrError(null, FormatError.E_need_login);


  let name = this.request.body.fields.name;
  let pid = this.request.body.fields.pid;
  let loc = yield cmdService.createLocation(name, pid);
  this.body = loc;
});